package com.hmjk.health.setting;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.HttpConf;
import com.hmjk.health.background.NetService;
import com.hmjk.health.card.LocaParamActivity;
import com.hmjk.health.card.LocationActivity;
import com.hmjk.health.card.ReminderActivity;
import com.hmjk.health.setting.system.AboutUsActivity;
import com.hmjk.health.setting.system.NewMessageNotificationActivity;
import com.hmjk.health.setting.system.UserManualActivity;
import com.hmjk.health.user.ChangePasswordActivity;
import com.hmjk.health.family.FamilyDetailActivity;
import com.hmjk.health.health.HealthDeviceParam;
import com.hmjk.health.health.HealthGlucoseTarget;
import com.hmjk.health.health.GlycoseHistoryActivity;
import com.hmjk.health.health.HealthCardBloodSugarAlarmGridActivity;
import com.hmjk.health.health.HealthCardBloodSugarGraph;
import com.hmjk.health.home.DeviceDetailActivity;
import com.hmjk.health.user.UserDetailActivity;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.FMEM_DATA;
import com.hmjk.health.util.MULTI_USER_DEV_DATA;
import com.hmjk.health.util.QRCodeActivity;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SettingActivity extends Activity implements OnClickListener{
	private HealthApp mApp = null;
	private ArrayList<FMEM_DATA> mMemListData;
	private String mFrom;
	private String mFid = "";
	private View shownView;
	private View shownDevView;
	
	//for dev card setting
	//private DEV_SET mSetData;
	private DEV_DATA mDev = null;
	
	/*health set*/
	private MULTI_USER_DEV_DATA mHealthAccount = null;
	private MULTI_USER_DEV_DATA mHealthMajor = null;
	private ImageView measureArrow;
	private LinearLayout measureLayout;
	private ImageView historyArrow;
	private LinearLayout historyLayout;
	private Animation openAnim;
	private Animation rotateDownAnim;
	private Animation rotateUpAnim;
	/*health set*/
	
	private TextView verNew = null;
	
	public static final int REQ_CHANGE_PWD = 41;
	public static final int REQ_DEVICE_MANAGER = 42;
	public static final int REQ_GLUCOSE_SETTING = 43;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		setContentView(R.layout.setting_activity);
		View fv = findViewById(R.id.set_family);
		View av = findViewById(R.id.set_account);
		View cv = findViewById(R.id.set_devcard);
		View hv = findViewById(R.id.set_healthaccount);
		View dv = findViewById(R.id.set_device);
		
		Intent i = getIntent();
		mFrom = i.getStringExtra("from");
		if(mFrom.equalsIgnoreCase("account")){
			fv.setVisibility(View.GONE);
			cv.setVisibility(View.GONE);
			hv.setVisibility(View.GONE);
			dv.setVisibility(View.GONE);
			shownView = av;
		}else if(mFrom.equalsIgnoreCase("family") || mFrom.equalsIgnoreCase("familycreator")){
			av.setVisibility(View.GONE);
			cv.setVisibility(View.GONE);
			hv.setVisibility(View.GONE);
			dv.setVisibility(View.GONE);
			String fid = i.getStringExtra("fid");
			mMemListData = new ArrayList<FMEM_DATA>();
			mFid = fid;
			shownView = fv;
			if(mFrom.equalsIgnoreCase("familycreator")){
				TextView tvQuit = (TextView)findViewById(R.id.quit);
				tvQuit.setText(R.string.dissolvefamily);
			}
		}else if(mFrom.equalsIgnoreCase("card")){
			av.setVisibility(View.GONE);
			fv.setVisibility(View.GONE);
			hv.setVisibility(View.GONE);
			dv.setVisibility(View.GONE);
			mDev = (DEV_DATA) i.getSerializableExtra("dev");
			
			shownView = cv;
		}else if(mFrom.equalsIgnoreCase("health_card")){
			mHealthAccount = (MULTI_USER_DEV_DATA) i.getSerializableExtra("dev");
			av.setVisibility(View.GONE);
			fv.setVisibility(View.GONE);
			cv.setVisibility(View.GONE);
			
			shownView = hv;
			measureArrow = (ImageView)shownView.findViewById(R.id.measure_reminder_arrow);
			measureLayout = (LinearLayout)shownView.findViewById(R.id.measure_reminder_sub);
			measureLayout.setVisibility(View.GONE);
			
			historyArrow = (ImageView)shownView.findViewById(R.id.health_history_arrow);
			historyLayout = (LinearLayout)shownView.findViewById(R.id.health_history_sub);
			historyLayout.setVisibility(View.GONE);
			
			openAnim = AnimationUtils.loadAnimation(this, R.anim.opendown);
			rotateDownAnim = AnimationUtils.loadAnimation(this, R.anim.rotate90down);
			rotateUpAnim = AnimationUtils.loadAnimation(this, R.anim.rotate90up);
			shownDevView = dv;
		}
		
		ImageButton back = (ImageButton)findViewById(R.id.back);
		back.setOnClickListener(this);
		
		View signOut = findViewById(R.id.sign_out);
		if(mFrom.equalsIgnoreCase("family") || mFrom.equalsIgnoreCase("familycreator") || mFrom.equalsIgnoreCase("account")){
			signOut.setVisibility(View.VISIBLE);
			signOut.setOnClickListener(this);
		}else{
			signOut.setVisibility(View.INVISIBLE);
		}
		View notify = findViewById(R.id.notify);
		notify.setOnClickListener(this);
		
		View manual = findViewById(R.id.usermanual);
		manual.setOnClickListener(this);
		
		View aboutus = findViewById(R.id.aboutus);
		aboutus.setOnClickListener(this);
		
		View version = findViewById(R.id.version);
		version.setOnClickListener(this);
		verNew = (TextView) version.findViewById(R.id.version_new);
		if(mApp.hasNewVersion()){
			verNew.setVisibility(View.VISIBLE);
		}else{
			verNew.setVisibility(View.INVISIBLE);
		}
		String pkName = getPackageName();
        String versionName = "unknown";
        try {
        	versionName = getPackageManager().getPackageInfo(pkName, 0).versionName;
			
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			versionName = "unknown";
		}
		TextView verHint = (TextView) version.findViewById(R.id.to_hint_ver);
		verHint.setText(versionName);
		
		View hotline = findViewById(R.id.hotline);
		hotline.setOnClickListener(this);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		registerReceiver(mReceiver, filter);
		if(mFrom.equalsIgnoreCase("account")){
			updateAccountView();
		}else if(mFrom.equalsIgnoreCase("family") || mFrom.equalsIgnoreCase("familycreator")){
			getMemberData();
			updateFamilyView();
		}else if(mFrom.equalsIgnoreCase("card")){
			getDeviceSetting();
			updateCardView();
		}else if(mFrom.equalsIgnoreCase("health_card")){
			getMajorAccount();
			updateHealthView();
			updateDeviceView();
		}
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(mReceiver);
		
		if(mFrom.equalsIgnoreCase("health_card")){
		if(measureLayout.getVisibility() == View.VISIBLE){
			hideSubView(measureLayout, measureArrow, false);
		}

		if(historyLayout.getVisibility() == View.VISIBLE){
			hideSubView(historyLayout, historyArrow, false);
		}
		}
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);	
				if(t.equals(DataManager.F_DEVICELIST)){		
					if(s && mFrom.equalsIgnoreCase("card")){
						getDeviceSetting();
						updateCardView();
					}
				}else if(t.equals(DataManager.F_DEVICE_SETTINGS)){
					String tid = intent.getStringExtra("tid");
					if(s && mFrom.equalsIgnoreCase("card") && tid.equals(mDev.id)){
						getDeviceSetting();
						updateCardView();
					}
				}
			}
		}
	};
	private void updateAccountView(){
		RelativeLayout userdata = (RelativeLayout) shownView.findViewById(R.id.userdata);
		RelativeLayout modifypwd = (RelativeLayout) shownView.findViewById(R.id.modifypwd);
		
		userdata.setOnClickListener(this);
		modifypwd.setOnClickListener(this);
	}
	
	private void updateDeviceView(){
		RelativeLayout invite = (RelativeLayout) shownDevView.findViewById(R.id.invite);
		invite.setOnClickListener(this);
		RelativeLayout devcalendar = (RelativeLayout) shownDevView.findViewById(R.id.healdevcalendar);
		devcalendar.setOnClickListener(this);
		RelativeLayout detail = (RelativeLayout) shownDevView.findViewById(R.id.healthdev_detail);
		detail.setOnClickListener(this);
		RelativeLayout health_param = (RelativeLayout) shownDevView.findViewById(R.id.health_param);
		health_param.setOnClickListener(this);
	}
	
	private void updateHealthView(){
		RelativeLayout setmajor = (RelativeLayout) shownView.findViewById(R.id.setmajor);
		setmajor.setOnClickListener(this);
		if((mHealthMajor != null) && mHealthMajor.sameWith(mHealthAccount)){
			setmajor.setVisibility(View.GONE);
		}
		
		RelativeLayout measure_reminder = (RelativeLayout) shownView.findViewById(R.id.measure_reminder);
		measure_reminder.setOnClickListener(this);
		TextView mgluc = (TextView)measureLayout.findViewById(R.id.measure_reminder_sub_gluc);
		mgluc.setOnClickListener(this);
		TextView mbp = (TextView)measureLayout.findViewById(R.id.measure_reminder_sub_bp);
		mbp.setOnClickListener(this);
	
		RelativeLayout drug_reminder = (RelativeLayout) shownView.findViewById(R.id.drug_reminder);
		drug_reminder.setOnClickListener(this);
		RelativeLayout gluc_range = (RelativeLayout) shownView.findViewById(R.id.gluc_range);
		gluc_range.setOnClickListener(this);
		
		RelativeLayout health_history = (RelativeLayout) shownView.findViewById(R.id.health_history);
		health_history.setOnClickListener(this);
		TextView hgluc = (TextView)historyLayout.findViewById(R.id.health_history_sub_gluc);
		hgluc.setOnClickListener(this);
		TextView hbp = (TextView)historyLayout.findViewById(R.id.health_history_sub_bp);
		hbp.setOnClickListener(this);
		
		TextView nameView = (TextView) shownView.findViewById(R.id.health_account_name);
		String name = getShownName();
		nameView.setText(name);
		
		//hide measure and drug reminder for first release
		measure_reminder.setVisibility(View.GONE);
		drug_reminder.setVisibility(View.GONE);
	}
	
	private String getShownName(){
		String name = null;
		if(mHealthAccount == null)
			return "";
		
		if((mHealthAccount.nick != null) && (mHealthAccount.nick.trim().length() > 0)){
			name = mHealthAccount.nick;
		}else{
			name = getResources().getString(R.string.noName);
			if((mHealthAccount.name != null) && (mHealthAccount.name.trim().length() > 0)){
				name = mHealthAccount.name;
			}
			
			name += " " + mHealthAccount.subcode;
		}
		return name;
	}
	
	private void updateCardView(){
		RelativeLayout invite = (RelativeLayout) shownView.findViewById(R.id.inviteloc);
		RelativeLayout devcalendar = (RelativeLayout) shownView.findViewById(R.id.devcalendar);
		RelativeLayout detail = (RelativeLayout) shownView.findViewById(R.id.detail);
		RelativeLayout history = (RelativeLayout) shownView.findViewById(R.id.history);
		RelativeLayout management = (RelativeLayout) shownView.findViewById(R.id.loc_dev_param);
		RelativeLayout activate = (RelativeLayout) shownView.findViewById(R.id.activate);
		TextView name = (TextView) shownView.findViewById(R.id.card_name);
		name.setText(mDev.name);
		
		invite.setOnClickListener(this);
		devcalendar.setOnClickListener(this);
		detail.setOnClickListener(this);
		history.setOnClickListener(this);
		management.setOnClickListener(this);
		activate.setOnClickListener(this);
		
		/*boolean isact = true;
		if(mSetData != null){
			isact = mSetData.active;
		}
		if((isact == false) && (mDev.admin == 1)){
			activate.setVisibility(View.VISIBLE);
		}else{
			activate.setVisibility(View.GONE);
		}*/
		activate.setVisibility(View.GONE); //DONOT need to activate device from MAPP side
	}
	
	private void updateFamilyView(){
		RelativeLayout fadata = (RelativeLayout) shownView.findViewById(R.id.fadata);
		//RelativeLayout famem = (RelativeLayout) shownView.findViewById(R.id.famembers);
		//TextView famemNum = (TextView) famem.findViewById(R.id.to_hint);
		
		RelativeLayout faquit = (RelativeLayout) shownView.findViewById(R.id.quitfa);
		RelativeLayout fabuild = (RelativeLayout) shownView.findViewById(R.id.buildfa);
		
		fadata.setOnClickListener(this);
		//famem.setOnClickListener(this);
		faquit.setOnClickListener(this);
		fabuild.setOnClickListener(this);
		
		if(mFid.isEmpty()){
			setViewEnabled(fadata,false);
			setViewEnabled(faquit,false);
			//String num = getResources().getString(R.string.Membernum, "0");
			//famemNum.setText(num);
			//setViewEnabled(famem,false);
		}else{
			setViewEnabled(fadata,true);
			setViewEnabled(faquit,true);
			//setViewEnabled(famem,true);
			//int size = mMemListData.size();
			//String sSize = "99+";
			//if(size <= 99){
			//	sSize = String.valueOf(size);
			//}
			//String num = getResources().getString(R.string.Membernum, sSize);
			//famemNum.setText(num);
		}
	}
	
	private void setViewEnabled(RelativeLayout parent, boolean enable){
		parent.setEnabled(enable);
		TextView first = (TextView) parent.getChildAt(0);
		first.setEnabled(enable);
	}
	
	private void getDeviceSetting(){
		//mSetData = null;
		String[] arg1 = new String[2];
		arg1[0] = "DEV_TID";
		arg1[1] = mDev.id;
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, arg1);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				if(ar.length() > 0){
					JSONObject e = ar.getJSONObject(0);
					mDev.id = e.getString("tid");
					mDev.name = e.getString("name");
						
					String ss = e.getString("status");
					mDev.status = Integer.parseInt(ss);
						
					mDev.type = e.getString("type");
						
					String a = e.getString("admin");
					mDev.admin = Integer.parseInt(a);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		
		/*String[] arg2 = new String[1];
		arg2[0] = mDev.id;
		
		DEV_SET[] data = (DEV_SET[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_SETTINGS, arg2);
		if(data != null){
			mSetData =  data[0];
		}*/
	}
	
	private void getMemberData(){
		if(mFid.isEmpty())
			return;
		
		JSONObject memjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYMEMBER, null);
		if(memjson != null){
			try {
				JSONArray ar = memjson.getJSONArray("array");
				int len = ar.length();
				mMemListData.clear();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					FMEM_DATA d = new FMEM_DATA();
					
					d.fid = e.getString("fid");
					if(d.fid.equals(mFid)){
						d.uid = e.getString("uid");
						d.name = e.getString("name");	
						d.status = e.getString("status");
						String b = e.getString("build");
						if(b.equals("1")){
							d.creator = true;
						}
						
						String a = e.getString("admin");
						if(a.equals("1")){
							d.admin = true;
						}
						
						mMemListData.add(d);
					}
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private boolean setMajorAccount(){
		SharedPreferences p = getSharedPreferences(SettingsConstants.GENERAL_SETTING, MODE_PRIVATE);
		SharedPreferences.Editor e = p.edit();
		String major = mHealthAccount.id + "-" + mHealthAccount.subcode;
		e.putString(SettingsConstants.KEY_HEALTH_MAJOR, major);
		return e.commit();
	}
	
	private void getMajorAccount(){
		SharedPreferences p = getSharedPreferences(SettingsConstants.GENERAL_SETTING, MODE_PRIVATE);
		String major = p.getString(SettingsConstants.KEY_HEALTH_MAJOR, "");
		if(major.trim().isEmpty()){
			mHealthMajor = null;
			return;
		}
		
		int pos = major.indexOf("-");
		if(pos <= 0){
			mHealthMajor = null;
			return;
		}
		
		String tid = major.substring(0, pos);
		String subcode = major.substring(pos+1);
			
		String[] arg1 = new String[2];
		arg1[0] = "DEV_TID";
		arg1[1] = tid;
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, arg1);
		if(devjson != null){
			try{
				JSONArray ar = devjson.getJSONArray("array");
				if(ar.length() > 0){
					JSONObject e = ar.getJSONObject(0);
					String type = e.getString("type");
					if(DEV_DATA.isHealthDev(type) == false){
						mHealthMajor = null;
						return;
					}
					
					mHealthMajor = new MULTI_USER_DEV_DATA();
					mHealthMajor.id = e.getString("tid");
					mHealthMajor.name = e.getString("name");
						
					String ss = e.getString("status");
					mHealthMajor.status = Integer.parseInt(ss);
						
					mHealthMajor.type = type;
						
					String a = e.getString("admin");
					mHealthMajor.admin = Integer.parseInt(a);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
			
		if(mHealthMajor == null)
			return;
			
		mHealthMajor.subcode = subcode;
			
		String[] args = new String[3];
		args[0] = "TID_SUBCODE";
		args[1] = mHealthMajor.id;
		args[2] = mHealthMajor.subcode;
		JSONObject subinfo = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICESUBINFO,args);
		if(subinfo != null){
			try {
				JSONArray subar = subinfo.getJSONArray("array");
				int sublen = subar.length();
				if(sublen > 0){
					JSONObject subone = subar.getJSONObject(0);
					
					mHealthMajor.nick = subone.getString("nickname");
					mHealthMajor.birthday = subone.getString("birthday");
					mHealthMajor.gender = subone.getString("gender");
					mHealthMajor.height = subone.getDouble("height");
					mHealthMajor.weight = subone.getDouble("weight");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}

	private void signOutConfirm(){
		String msg = getResources().getString(R.string.signOutConfirm);
		mApp.showConfirmDialog(this, msg, new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				if(v.getId() == R.id.alert_but1){
					mApp.showWaitting(SettingActivity.this, null);
					Intent si = new Intent(SettingActivity.this, NetService.class);
					si.setAction(NetService.SIGN_OUT_ACCOUNT);
					Time t = new Time();
					t.setToNow();
					String stamp = "SIGN_OUT_ACCOUNT" + t.toString(); 
					si.putExtra("stamp",stamp);
					mApp.addNetHandler(stamp,mHandler);
					startService(si);
				}
			}
			
		});
	}
	
	@Override  
    protected void onActivityResult(int requestCode, int resultCode, Intent i) {
		
		if (requestCode == REQ_CHANGE_PWD && resultCode == RESULT_OK){
			finish();
		}else if(requestCode == REQ_DEVICE_MANAGER && resultCode == RESULT_OK){
			String action = i.getAction();
			if(action.equals("COMMIT_DEVICE_INTEREST_ABORT")){
				/*String tid = i.getStringExtra("tid");
				Intent intent = new Intent(action);
				intent.putExtra("tid", tid);
				setResult(RESULT_OK,intent);*/
				finish();
			}
		}else if(requestCode == REQ_GLUCOSE_SETTING && resultCode == RESULT_OK){
			finish();
		}
	};
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		case R.id.sign_out:{
			signOutConfirm();
			
			//mApp.signOut();
			//setResult(RESULT_OK);
			//finish();
		}break;
		
		//account settings
		case R.id.userdata:{
			Intent i = new Intent(this,UserDetailActivity.class);
			startActivity(i);
		}break;
		case R.id.modifypwd:{
			Intent i = new Intent(this,ChangePasswordActivity.class);
			startActivityForResult(i, REQ_CHANGE_PWD);
		}break;
		
		//family settings
		case R.id.fadata:{
			//TODO:show family detail
			Intent i = new Intent(this,FamilyDetailActivity.class);
			startActivity(i);
		}break;
		/*case R.id.famembers:{
			//TODO:show all members
		}break;*/
		case R.id.quitfa:{
			Intent i = new Intent("QUIT_FA");
			setResult(RESULT_OK,i);
			finish();
		}break;
		case R.id.buildfa:{
			Intent i = new Intent("BUILD_FA");
			setResult(RESULT_OK,i);
			finish();
		}break;
		//device card
		case R.id.detail:{
			//show device detail
			Intent i = new Intent(this,DeviceDetailActivity.class);
			i.putExtra("dev", mDev);
			startActivity(i);
		}break;
		case R.id.history:{
			Intent i = new Intent(this,LocationActivity.class);
			i.putExtra("tid", mDev.id);
			startActivity(i);
		}break;
		case R.id.loc_dev_param:{
			Intent i = new Intent(this,LocaParamActivity.class);
			i.putExtra("dev", mDev);
			startActivityForResult(i, REQ_DEVICE_MANAGER);
		}break;
		case R.id.activate:{
			/*mApp.showWaitting(this, null);
			Intent si = new Intent(this, NetService.class);
			si.setAction(NetService.ACTIVATE_DEVICE);
			si.putExtra("uid", mApp.getUID());
			si.putExtra("tid", mDev.id);
			
			Time t = new Time();
			t.setToNow();
			String stamp = "ACTIVATE_DEVICE" + t.toString(); 
			si.putExtra("stamp",stamp);
			mApp.addNetHandler(stamp,mHandler);
			startService(si);*/
		}break;
		
		//health settings
		case R.id.setmajor:{
			mApp.showConfirmDialog(this, getResources().getString(R.string.health_set_major_hint, getShownName()), new OnClickListener() {
				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					
					if(view.getId() == R.id.alert_but1){
						if(setMajorAccount()){
							mApp.showAlertDialog(SettingActivity.this, getResources().getString(R.string.family_set_ok), R.string.Yes, new OnClickListener(){
								@Override
								public void onClick(View arg0) {
									finish();
								}
								
							});
						}else{
							mApp.showAlertDialog(SettingActivity.this, R.string.family_set_err);
						}
					}
				}
			});			
		}break;
		case R.id.inviteloc:{
			String uri = HttpConf.getDeviceInterestUri(mDev.id, mDev.name);
			Intent i = new Intent(this,QRCodeActivity.class);
			i.putExtra("type", QRCodeActivity.TYPE_DEVICE);
			i.putExtra("uri", uri);
			i.putExtra("mid",-1);
			startActivity(i);
		}break;
		case R.id.invite:{
			String uri = HttpConf.getDeviceInterestUri(mHealthAccount.id, mHealthAccount.name);
			Intent i = new Intent(this,QRCodeActivity.class);
			i.putExtra("type", QRCodeActivity.TYPE_DEVICE);
			i.putExtra("uri", uri);
			i.putExtra("mid",-1);
			startActivity(i);
			//finish();
		}break;
		case R.id.healthdev_detail:{
			Intent i = new Intent(this,DeviceDetailActivity.class);
			i.putExtra("dev", mHealthAccount);
			startActivity(i);
		}break;
		case R.id.measure_reminder:{
			if(measureLayout.getVisibility() == View.VISIBLE){
				hideSubView(measureLayout, measureArrow, true);
			}else{
				hideSubView(historyLayout, historyArrow, true);
				showSubView(measureLayout, measureArrow);
			}
		}break;
		
		case R.id.measure_reminder_sub_gluc:
			Intent ih = new Intent(SettingActivity.this,HealthCardBloodSugarAlarmGridActivity.class);
			startActivity(ih);

			break;
			
		case R.id.measure_reminder_sub_bp:
			Intent ibp = new Intent(SettingActivity.this,HealthCardBloodSugarGraph.class);
			startActivity(ibp);

			break;
		
		case R.id.health_history:{
			if(historyLayout.getVisibility() == View.VISIBLE){
				hideSubView(historyLayout, historyArrow, true);
			}else{
				hideSubView(measureLayout, measureArrow, true);
				showSubView(historyLayout, historyArrow);
			}
		}break;
		
		case R.id.health_history_sub_gluc:
		{
			Intent i = new Intent(this, GlycoseHistoryActivity.class);
			i.putExtra("tid", mHealthAccount.id);
			i.putExtra("subcode", mHealthAccount.subcode);
			i.putExtra("nickname", mHealthAccount.nick);
			i.putExtra("entry", "gluc");
			startActivity(i);
		}
		break;
		
		case R.id.health_history_sub_bp:{
			Intent i = new Intent(this, GlycoseHistoryActivity.class);
			i.putExtra("tid", mHealthAccount.id);
			i.putExtra("subcode", mHealthAccount.subcode);
			i.putExtra("nickname", mHealthAccount.nick);
			i.putExtra("entry", "bp");
			startActivity(i);
		}break;
		
		case R.id.health_param:{
			Intent i = new Intent(this, HealthDeviceParam.class);
			i.putExtra("tid", mHealthAccount.id);
			i.putExtra("subcode", mHealthAccount.index);
			i.putExtra("admin", mHealthAccount.admin);
			startActivityForResult(i, REQ_GLUCOSE_SETTING);
		}break;
		
		//system settings
		case R.id.notify:{
			//TODO:set ring or viberate for notification
			Intent i = new Intent(this, NewMessageNotificationActivity.class);
			startActivity(i);
		}break;
		case R.id.usermanual:{
		Intent i = new Intent(this,UserManualActivity.class);
		startActivity(i);
		}break;
		case R.id.aboutus:{
			//TODO:develop team intro
			Intent i = new Intent(this, AboutUsActivity.class);
			startActivity(i);
		}break;
		case R.id.version:{
			//if(verNew.getVisibility() == View.VISIBLE){
			//	mApp.checkNewVersion(true);
			//}
			upgradeVersion();
		}break;
		case R.id.hotline:{
			
		}break;
		case R.id.gluc_range:{
			Intent i = new Intent(this, HealthGlucoseTarget.class);
			i.putExtra("tid", mHealthAccount.id);
			i.putExtra("subcode", mHealthAccount.subcode);
			i.putExtra("admin", mHealthAccount.admin);
			startActivityForResult(i, REQ_GLUCOSE_SETTING);
		}break;
		case R.id.devcalendar:{
			Intent i = new Intent(this,ReminderActivity.class);
			i.putExtra("tid", mDev.id);
			if(mDev.admin == 1){
				i.putExtra("isAdmin", true);
			}else {
				i.putExtra("isAdmin", false);
			}
			startActivity(i);
		}break;
		case R.id.healdevcalendar:{
			Intent i = new Intent(this,ReminderActivity.class);
			i.putExtra("tid", mHealthAccount.id);
			if(mHealthAccount.admin == 1){
				i.putExtra("isAdmin", true);
			}else {
				i.putExtra("isAdmin", false);
			}
			startActivity(i);
		}break;
		}
		
	}
	
	private void hideSubView(View layout, ImageView arrow, boolean anim){
		layout.clearAnimation();
		layout.setVisibility(View.GONE);
		if(anim){
			arrow.startAnimation(rotateUpAnim);
		}else{
			arrow.clearAnimation();
		}
	}
	
	private void showSubView(View layout, ImageView arrow){
		layout.setVisibility(View.VISIBLE);
		arrow.startAnimation(rotateDownAnim);
		layout.startAnimation(openAnim);
	}
	
	private void upgradeVersion(){
		mApp.showWaitting(this, null);
		UmengUpdateAgent.setDefault();
		UmengUpdateAgent.setUpdateAutoPopup(true);
		UmengUpdateAgent.setUpdateUIStyle(UpdateStatus.STYLE_DIALOG);
		UmengUpdateAgent.setDeltaUpdate(false);
		UmengUpdateAgent.setUpdateListener(new UmengUpdateListener(){

		@Override
		public void onUpdateReturned(int status, UpdateResponse updateInfo) {
			mApp.dismissWaiting();
			switch(status){
				case UpdateStatus.Yes:
					mApp.setNewVersion(true);
					UmengUpdateAgent.showUpdateDialog(SettingActivity.this, updateInfo);
					break;
				case UpdateStatus.No:
					mApp.showUmengNoUpgradeDialog(SettingActivity.this);
					break;
				case UpdateStatus.NoneWifi:
					Toast.makeText(SettingActivity.this, R.string.no_network_hint, Toast.LENGTH_SHORT).show();
					break;
				case UpdateStatus.Timeout:	
					Toast.makeText(SettingActivity.this, R.string.network_timeout, Toast.LENGTH_SHORT).show();
					break;
				}
			}
			
		});
		
		UmengUpdateAgent.forceUpdate(this);
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				if(stamp.startsWith("SIGN_OUT_ACCOUNT")){
					mApp.dismissWaiting();
					Intent i = new Intent("SIGN_OUT");
					setResult(RESULT_OK,i);
					finish();
				}else if(stamp.startsWith("ACTIVATE_DEVICE")){
					String sjson = b.getString("json");
					if(sjson != null){
						mApp.dismissWaiting();
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								if(state.equals("00")){
									Intent i = new Intent("ACTIVATE_DEVICE_OK");
									i.putExtra("tid", mDev.id);
									setResult(RESULT_OK,i);
									finish();
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mApp.showAlertDialog(SettingActivity.this, R.string.activateDevFail);
					}
				}
			}
			break;
			}
		}
	};
}
